package cj.web.admin.controllers;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.record.formula.functions.Row;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.admin.dao.SurveyDepotItemDAO;
import cj.web.admin.dao.SurveyDepotSubjectDAO;
import cj.web.admin.dao.SurveyDepotTypeDAO;
import cj.web.admin.domain.SurveyDepotSubject;
import cj.web.admin.domain.SurveyDepotType;
import cj.web.constants.MemuEnum;
import cj.web.constants.SurveyTypeEnum;
import cj.web.login.controllers.BaseController;

/**
 * 题库
 * @author Administrator
 *
 */
@Path("/surveyDepot")
public class SurveyDepotController extends BaseController{

	private static Logger logger = Logger.getLogger(SurveyDepotController.class.getName());
	
	@Autowired
	private SurveyDepotItemDAO surveyDepotItemDao;
	@Autowired
	private SurveyDepotSubjectDAO surveyDepotSubjectDao;
	@Autowired
	private SurveyDepotTypeDAO surveyDepotTypeDAO;
	
	@Get("show")
	public String show(Model model, HttpServletRequest request) {
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgtk);
		return "/views/survey/surveyDepotList.vm";
	}

	@Post("getList")
	public String queryList(SurveyDepotType survey) {
	
		List<SurveyDepotType> arr = surveyDepotTypeDAO.query(survey);
		
		JSONObject jo = new JSONObject();
		
		int size = surveyDepotTypeDAO.querysize(survey);
		
		jo.put("data", arr);
		jo.put("draw", survey.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model){
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgtk);
		return "/views/survey/surveyDepotDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,SurveyDepotType survey,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			survey.setCreateUser(returnSessionObj(request).getAccount());
			survey.setUpdateUser(returnSessionObj(request).getAccount());
			surveyDepotTypeDAO.create(survey);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id){
		
		SurveyDepotType survey =surveyDepotTypeDAO.queryById(id);
		
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgtk);
        model.add("obj",survey);
		return "/views/survey/surveyDepotEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,SurveyDepotType survey,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			survey.setUpdateUser(returnSessionObj(request).getAccount());
			surveyDepotTypeDAO.update(survey);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("id") int id){
		surveyDepotTypeDAO.deleteById(id);
		return "r:show";
	}
	
	//--------surveySubject--------
	@Get("showSj")
	public String showSubject(Model model,@Param("id") int id, HttpServletRequest request) {
		SurveyDepotType survey =surveyDepotTypeDAO.queryById(id);
		//MemuEnum
		model.add("surveyDepotId",id);
		model.add("vote",survey);
        model.add("MemuEnum",MemuEnum.lkgtk);
        model.add("isMutilEnum",EnumSet.allOf(SurveyTypeEnum.class));
		return "/views/survey/surveyDepotSubjectList.vm";
	}

	@Post("getSjList")
	public String querySubjectList(SurveyDepotSubject surveySubject) {
		JSONObject jo = new JSONObject();
		List<Map> arr = surveyDepotSubjectDao.query(surveySubject);
		int size = surveyDepotSubjectDao.querysize(surveySubject);
		
		jo.put("data", arr);
		jo.put("draw", surveySubject.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	@Get("createSjPage")
	public String createSubjectPage(Model model,@Param("surveyDepotId") int surveyDepotId){
		//MemuEnum
		model.add("surveyDepotId",surveyDepotId);
        model.add("MemuEnum",MemuEnum.lkgtk);
        model.add("SurveyTypeEnum",EnumSet.allOf(SurveyTypeEnum.class));
		return "/views/survey/surveyDepotSubjectDetail.vm";
	}
	
	@Post("createSj")
	public String createSubject(Model model, @Param("surveyDepotId")int surveyDepotId, @Param("isMutil")int isMutil, 
			@Param("subject")String subject,@Param("resolving")String resolving, @Param("answer")List<Integer> answers, @Param("item")List<String> items, @Param("count")int count, HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if(isMutil == 2){
			items.add("正确");
			items.add("错误");
		}
		
		try {
			String l_answers = "";//存放考试头答案信息
			String user = returnSessionObj(request).getAccount();
			int subjectId = surveyDepotSubjectDao.create(surveyDepotId, isMutil, subject, user,count,resolving);
			
			for(int i = 0; i < items.size(); i++){
				String item = items.get(i);
				int answer = answers.get(i).intValue();
				int surveyDepotItemId = surveyDepotItemDao.create(surveyDepotId, subjectId, item, user, i, answer);
				
				if(answer==1){
					l_answers+=surveyDepotItemId+"@";
				}
			}
			//更新答案
//			surveyDepotSubjectDao.update(subjectId, l_answers);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("editSj")
	public String editSubject(Model model,@Param("id") int id){
		
		SurveyDepotSubject surveySubject =surveyDepotSubjectDao.queryById(id);
		int subjectDepotId = surveySubject.getId().intValue();
		List<Map> items = surveyDepotItemDao.queryBySubjectId(subjectDepotId);
		
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgtk);
        model.add("SurveyTypeEnum",EnumSet.allOf(SurveyTypeEnum.class));
        model.add("Subject",surveySubject);
        model.add("Items",items);
		return "/views/survey/surveyDepotSubjectEdit.vm";
	}
	
	@Post("updateSj")
	public String updateSubject(Model model, @Param("subjectDepotId")int subjectDepotId, @Param("isMutil")int isMutil, 
			@Param("subject")String subject,@Param("resolving")String resolving, @Param("id")List<Integer> ids, @Param("item")List<String> items, @Param("answer")List<Integer> answers, @Param("count")int count, 
			HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if(isMutil == 2){
			items.add("正确");
			items.add("错误");
		}
		String user = returnSessionObj(request).getAccount();
		SurveyDepotSubject origSub =surveyDepotSubjectDao.queryById(subjectDepotId);
		
		surveyDepotItemDao.deleteBySubId(subjectDepotId); //逻辑删除所有原item
		
		try {
			surveyDepotSubjectDao.update(subjectDepotId, isMutil, subject, user, count,resolving);
			if( null != items && items.size() > 0 ){
				for(int i = 0; i < items.size(); i++){
					String item = items.get(i);
					int itemId = ids.get(i).intValue();
					if(itemId > -1){
						surveyDepotItemDao.update(itemId, item, user, i, answers.get(i).intValue());
					}
					else{
						surveyDepotItemDao.create(origSub.getSurveyDepotId(), subjectDepotId, item, user, i, answers.get(i).intValue());
					}
				}
			}
			
			String l_answers = "";//存放考试头答案信息
			List<Integer> surveyDepotItemIds = surveyDepotItemDao.queryIdBySubjectId(subjectDepotId);
			if(surveyDepotItemIds!=null && surveyDepotItemIds.size()>0){
				for(Integer surveyDepotItemId:surveyDepotItemIds){
					l_answers+=surveyDepotItemId+"@";
				}
			}
			//更新答案
//			surveyDepotSubjectDao.deleteById(subjectDepotId);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteSjById")
	public String deleteSubjectById(Model model,@Param("id") int id){
		
		SurveyDepotSubject surveySubject =surveyDepotSubjectDao.queryById(id);
		
		if(surveySubject!=null)
		{
			surveyDepotSubjectDao.deleteById(id);
		}
		
		return "r:showSj?id="+surveySubject.getSurveyDepotId();
	}
	
	@Get("surveyUploadSt")
	public String surveyUploadSt(Model model){
		model.add("MemuEnum", MemuEnum.lkgstdr);
		List<SurveyDepotType> objs = surveyDepotTypeDAO.queryAll();
		model.add("objs", objs);        
		return "/views/survey/surveyDepotSubjectUpload";
	}
	
	@Post("uploadSt")
	public String upload(@Param("id") int id,@Param("uploadExcel") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (!file.isEmpty()) {  
            try {  
                InputStream inputStream = file.getInputStream();
                List<Map> importExcelResult =  importExcel(inputStream);
                for(Map result:importExcelResult){
                	int isMutil = 0;
                	List<String> items = new ArrayList<String>();
                	List<Integer> answers = new ArrayList<Integer>();
                	if(result.get("isMutil").toString().equals("单选")){
                		isMutil=0;
                		items.add("A."+result.get("A").toString());
                		items.add("B."+result.get("B").toString());
                		items.add("C."+result.get("C").toString());
                		items.add("D."+result.get("D").toString());
                		
                		if("A".equals(result.get("answer").toString())){
                			answers.add(1);
                		}else{
                			answers.add(0);
                		}
                		
                		if("B".equals(result.get("answer").toString())){
                			answers.add(1);
                		}else{
                			answers.add(0);
                		}
                		
                		if("C".equals(result.get("answer").toString())){
                			answers.add(1);
                		}else{
                			answers.add(0);
                		}
                		
                		if("D".equals(result.get("answer").toString())){
                			answers.add(1);
                		}else{
                			answers.add(0);
                		}
                		
                    }else if(result.get("isMutil").toString().equals("多选")){
                    	isMutil=1;
                    	items.add("A."+result.get("A").toString());
                		items.add("B."+result.get("B").toString());
                		items.add("C."+result.get("C").toString());
                		items.add("D."+result.get("D").toString());
                		
                		if(result.get("answer").toString().indexOf("A")==-1){
                			answers.add(0);
                		}else{
                			answers.add(1);
                		}
                		
                		if(result.get("answer").toString().indexOf("B")==-1){
                			answers.add(0);
                		}else{
                			answers.add(1);
                		}
                		
                		if(result.get("answer").toString().indexOf("C")==-1){
                			answers.add(0);
                		}else{
                			answers.add(1);
                		}
                		
                		if(result.get("answer").toString().indexOf("D")==-1){
                			answers.add(0);
                		}else{
                			answers.add(1);
                		}
                    }else if(result.get("isMutil").toString().equals("判断题")){
                    	isMutil=2;
                    	items.add("A."+result.get("A").toString());
                		items.add("B."+result.get("B").toString());
                		
                		if("A".equals(result.get("answer").toString())){
                			answers.add(1);
                		}else{
                			answers.add(0);
                		}
                		
                		if("B".equals(result.get("answer").toString())){
                			answers.add(1);
                		}else{
                			answers.add(0);
                		}
                    }
                    String subject = result.get("subject").toString();
                    int count = result.get("answer").toString().length();
                    String answerStr = result.get("answer").toString();
                    String resolving = "正确答案："+answerStr+"<br>答案解析："+result.get("resolving").toString();
                    String user = returnSessionObj(request).getAccount();
        			int subjectId = surveyDepotSubjectDao.
        					create(id, isMutil, subject, user,count,resolving);
        			
        			for(int i = 0; i < items.size(); i++){
        				String item = items.get(i);
        				int answer = answers.get(i).intValue();
        				int surveyDepotItemId = surveyDepotItemDao.create(id, subjectId, item, user, i, answer);
        			}
                }
            } catch (Exception e) {  
                e.printStackTrace();  
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
        return "r:surveyUploadSt";
    }
	
	// 拿到输入文件的输入流，把流拿到这个下面的这个方法
	public static List<Map>  importExcel(InputStream inputStream) throws IOException {
	     
          // 获取当年
          int year =  Calendar.getInstance().get(Calendar.YEAR);
          String valueOf = String.valueOf(year);
          // 定义一个List，用来存放excel表中的值
          List<Map> list2= new  ArrayList<Map>();

          // 1、传入获取的工作流, workbook,是一个工作簿，使用excel能操作的这边它都可以操作，这一个操作，相当于是把Excel放到Java中使用
          //Workbook wb = new XSSFWorkbook(inputStream);
          HSSFWorkbook wb = new HSSFWorkbook(inputStream);

          // 2、获取工作簿中的表,对表中的设置，通过下标去拿第一张表
          HSSFSheet sheet = wb.getSheetAt(0);
          // 3、获取表格总的行数
          int rowNumber = sheet.getPhysicalNumberOfRows();
               // 从第二行开始读取每一行数据，我们设置的模板表头是在第一、第二行，下标从0开始。
               for (int rowNum = 1; rowNum < rowNumber;  rowNum++) {
                   // 每读取一行,实例化一个对象
                   Map map1=  new HashMap();
                   // 获取工作表中第二行的数据
                   HSSFRow rowData = sheet.getRow(rowNum);
                   // 这个地方，要注意，取到的值要进行判空处理,同时也要对值的类型进行转换
                   if (rowData != null) {     
	                  map1.put("isMutil", rowData.getCell(3));//单选多选
	                  map1.put("subject", rowData.getCell(4));//题目
	                  map1.put("A", rowData.getCell(5));//选项A
	                  map1.put("B", rowData.getCell(6));//选项B
	                  map1.put("C", rowData.getCell(7));//选项C
	                  map1.put("D", rowData.getCell(8));//选项D
	                  map1.put("answer", rowData.getCell(9));//答案
	                  map1.put("resolving", rowData.getCell(11));//解析
//	                  int surveyDepotItemId = surveyDepotItemDao.create(surveyDepotId, subjectId, item, user, i, answer);
	      				
	                      
                      list2.add(map1);
                   }
              }
          // 循环结束后，把从excel表读取的对象放到excelList中。
          // 关闭流
          inputStream.close();

          // 返回list结果
          return list2;
     }
}